package com.bookstore.servlet;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

//要给Servlet 添加一个URL映射
//http://www.bookstore.com:80/
//http://www.bookstore.com:80/client/register.do
@WebServlet("/client/register.do")
public class RegisterServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    //重写两个方法：1.doGet 2.doPost

    /**
     * @param request  代表本次请求中 所有浏览器发来的数据 都封装在该对象中
     * @param response 代表本次请求中 所有即将发给浏览器的响应数据 都封装在该对象中
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应的字符编码
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String gender = request.getParameter("gender");
        String email = request.getParameter("email");
        String telephone = request.getParameter("telephone");
        String introduce = request.getParameter("introduce");

        User user = new User(null, username, password, gender, email, telephone, introduce, null, 0, 0, new Date());
        int result = userService.registUser(user);
        //1.获取响应对象的字符输出流
        PrintWriter writer = response.getWriter();
        if (result > 0) {
            writer.write("<h1>用户" + username + "注册成功！</h1>");
        } else {
            writer.write("<h1>用户" + username + "注册失败！</h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
